//  this library.
import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_svg/svg.dart';
import 'package:hktk_app/dao/industry_dao.dart';
import 'package:hktk_app/dao/my_dao.dart';
import 'package:hktk_app/dao/package_dao.dart';
import 'package:hktk_app/decoration/home/tab_decoration.dart';
import 'package:hktk_app/dialog/buy_dialog.dart';
import 'package:hktk_app/model/home/exam_key_model.dart';

// 非游客模式
class PackageList extends StatefulWidget {
  PackageList({Key? key}) : super(key: key);

  @override
  State<StatefulWidget> createState() => _PackageListState();
}

class _PackageListState extends State<PackageList>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  late Future<dynamic> _list;
  late Future<dynamic> _list1;
  late BuildContext _context;

  @override
  Widget build(BuildContext context) {
    _context = context;
    int activeIndex = 0;

    // 
    return Scaffold(
        appBar: AppBar(
          title: Text(
            '${DateTime.now().year}最新版...',
            textAlign: TextAlign.center,
            style: TextStyle(
              color: Colors.black,
              fontSize: 18,
              fontWeight: FontWeight.w500,
              letterSpacing: 0.36,
            ),
          ),
          // backgroundColor: Color(0xFFFFFFF6),
          // 设置背景颜色
          leading: IconButton(
            icon: SvgPicture.asset(
              'images/back/back1.svg', // 替换为你的 SVG 文件路径
              width: 20,
              height: 20,
            ), // 左侧图标
            onPressed: () {
              // 处理点击事件
              // ScaffoldMessenger.of(context).showSnackBar(
              //   SnackBar(content: Text('菜单按钮被点击')),
              // );
              Navigator.pop(context);
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: SvgPicture.asset(
                'images/back/fresh.svg', // 替换为你的 SVG 文件路径
                width: 20, // 设置 SVG 图片的宽度
                height: 20, // 设置 SVG 图片的高度
              ), // 右侧第一个图标
              onPressed: () {
                // 处理点击事件
                // ScaffoldMessenger.of(context).showSnackBar(
                //   SnackBar(content: Text('搜索按钮被点击')),
                // );
                setState(() {
                ExamKeyModel examKeyModel = IndustryDao.getExamKey();
                _list = PackageDao.listByExam(examId: examKeyModel.examId);
                _list1 = PackageDao.listByExam(examId: examKeyModel.examId);
                });
              },
            ),
            IconButton(
              icon: Icon(Icons.notifications), // 右侧第二个图标
              onPressed: () {
                // 处理点击事件
                // ScaffoldMessenger.of(context).showSnackBar(
                //   SnackBar(content: Text('通知按钮被点击')),
                // );
              },
            ),
          ],
          elevation: 4.0,
          // 设置阴影高度
          centerTitle: true,
          // 标题居中
          toolbarHeight: 60.0,
          // 设置工具栏高度

          titleSpacing: 0.0,
          // 移除默认的 title 间距
          bottom: PreferredSize(
            preferredSize: Size.fromHeight(0.0), // 移除底部内边距
            child: Container(),
          ),
        ),
        body: Container(
          width: 1.0.sw,
          decoration: BoxDecoration(color: Color(0xFFF6F6F6)),
          child: Column(children: [
            Container(
              decoration: BoxDecoration(color: Color(0xFFFFFFFF)),
              padding: EdgeInsets.only(
                  left: 10.0.w, right: 10.0.w, top: 8.0.h, bottom: 8.0.h),
              child: TabBar(
                // indicator: UnderlineTabIndicator(
                //   borderSide: BorderSide.none, // 去掉下划线
                // ),
                // indicator: _CustomTabIndicator(),
                indicator: RoundedBackgroundDecoration(
                    borderRadius: 22.0.w, color: Color(0xFFFFF4F4)),
                labelColor: Color(0xFFE6494E),
                unselectedLabelColor: Colors.grey,
                dividerHeight: 0,

                controller: _tabController,
                tabs: [
                  _createTabBarView(index: 0, activeIndex: activeIndex),
                  _createTabBarView(index: 1, activeIndex: activeIndex),
                ],
              ),
            ),
            // Container(margin: EdgeInsets.only(top: 10.0.w),),
            Container(
              height: 1.0.sh -
                  ScreenUtil().statusBarHeight -
                  60 -
                  (8.h * 2) -
                  (3 * 2) -
                  15 -
                  ScreenUtil().bottomBarHeight -
                  15,
              child: TabBarView(
                controller: _tabController,
                children: [
                  _createTabBarViewFutureBuilder(_list),
                  _createTabBarViewFutureBuilder(_list1),
                ],
              ),
            ),
          ]),
        ));
  }

  @override
  void initState() {
    // controller = AnimationController(
    //   duration: const Duration(seconds: 2),
    //   vsync: this, // 使用 SingleTickerProviderStateMixin 提供的 Ticker
    // );
    //
    // animation = Tween<double>(begin: 0, end: 300).animate(controller)
    //   ..addListener(() {
    //     setState(() {
    //       // 强制重建以更新动画
    //     });
    //   });
    super.initState();
    ExamKeyModel examKeyModel = IndustryDao.getExamKey();
    _list = PackageDao.listByExam(examId: examKeyModel.examId);
    _list1 = PackageDao.listByExam(examId: examKeyModel.examId);
    _tabController = TabController(length: 2, vsync: this);
  }

  @override
  void dispose() {
    _tabController.dispose();

    super.dispose();
  }

  FutureBuilder _createTabBarViewFutureBuilder(Future<dynamic> f) {
    return FutureBuilder(
        future: f,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.data == null) return Container();
            var list = snapshot.data;

            return Container(
                margin: EdgeInsets.only(top: 10),
                decoration: BoxDecoration(color: Colors.white),
                child: ListView.builder(
                  itemBuilder: (context, index) {
                    return Container(
                      width: 1.0.sw,
                      padding: EdgeInsets.only(left: 16.0.w, right: 16.0.w),
                      child: Row(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Image.asset(
                            "images/test/2.jpg",
                            width: 150.0.w,
                            height: 150.0.w,
                          ),
                          Expanded(
                              child: Padding(
                                  padding: EdgeInsets.only(
                                      left: 5, top: 5, bottom: 5),
                                  child: Column(
                                    crossAxisAlignment:
                                        CrossAxisAlignment.start,
                                    spacing: 10,
                                    mainAxisAlignment: MainAxisAlignment.start,
                                    children: [
                                      Text(list[index].name),
                                      Wrap(
                                        spacing: 10,
                                        runSpacing: 5,
                                        children: [
                                          // tagNameList可能为null，非数组格式
                                          if(list[index]
                                              .tagNameList!=null)
                                          for (var i = 0;
                                              i <
                                                  list[index]
                                                      .tagNameList
                                                      .length;
                                              i++)
                                            Container(
                                              padding: EdgeInsets.all(5),
                                              decoration: BoxDecoration(
                                                  color: Color(0xFFFFF2E1),
                                                  borderRadius:
                                                      BorderRadius.circular(8)),
                                              child: Text(
                                                list[index].tagNameList[i],
                                              ),
                                            ),
                                        ],
                                      ),
                                      Row(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.center,
                                        mainAxisAlignment:
                                            MainAxisAlignment.spaceBetween,
                                        children: [
                                          Container(
                                              width: 78.76.w,
                                              height: 24.h,
                                              padding: EdgeInsets.only(left: 2),
                                              decoration: BoxDecoration(
                                                image: DecorationImage(
                                                    image: AssetImage(
                                                        "images/test/3.png"),
                                                    fit: BoxFit.cover),
                                              ),
                                              child: Align(
                                                alignment: Alignment.centerLeft,
                                                child: Text(
                                                  "折扣价: ${list[index].discountPrice / 100}",
                                                  style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: 10.sp),
                                                ),
                                              )),
                                          Column(
                                            crossAxisAlignment:
                                                CrossAxisAlignment.start,
                                            children: [
                                              Text(
                                                  "￥${list[index].discountPrice / 100}",
                                                  style: TextStyle(
                                                    color: Color(0xFFF64E3A),
                                                    fontSize: 20.sp,
                                                    fontWeight: FontWeight.w500,
                                                    letterSpacing: 0.40,
                                                  )),
                                              // Text("1111")
                                            ],
                                          )
                                        ],
                                      ),
                                      Row(
                                        mainAxisAlignment:
                                            MainAxisAlignment.end,
                                        children: [
                                          Padding(padding: EdgeInsets.only(right: 0),child: Container(
                                            height: 22,
                                            padding: const EdgeInsets.symmetric(
                                                horizontal: 10, vertical: 2),
                                            decoration: ShapeDecoration(
                                              color: Color(0xFF3C6CFF),
                                              shape: RoundedRectangleBorder(
                                                borderRadius:
                                                BorderRadius.circular(90),
                                              ),
                                            ),
                                            alignment: Alignment.center,
                                            child: GestureDetector(onTap: (){

                                            //
                                              var height = ScreenUtil().screenHeight;
                                              double sheetHeight = height * 0.8;

                                              // 判断ios与android判断
                                              // /version/current
                                              () async{

                                                  bool flag=await MyDao.versionCurrentIos();

                                                if(mounted){
                                                  // 弹出层
                                                  showModalBottomSheet(
                                                    context: _context,
                                                    // 设置底部弹出框全屏显示
                                                    isScrollControlled: true,
                                                    // 自定义弹出层高度
                                                    constraints: BoxConstraints(maxHeight: sheetHeight),
                                                    // 自定义圆角
                                                    shape: RoundedRectangleBorder(
                                                      borderRadius: BorderRadius.only(
                                                        topLeft: Radius.circular(24),
                                                        topRight: Radius.circular(24),
                                                      ),
                                                    ),
                                                    builder: (BuildContext context) {
                                                      return BuyDialog(
                                                        package: list[index],
                                                        index: index,
                                                        payHide: flag,
                                                      );
                                                    },
                                                  );
                                                }


                                              }();




                                            },child:Text(
                                              '立即领取',
                                              style: TextStyle(
                                                color: Colors.white,
                                                fontSize: 12,
                                                fontWeight: FontWeight.w400,
                                                letterSpacing: 0.12,
                                              ),
                                            )),
                                          ),)

                                        ],
                                      )
                                    ],
                                  )))
                        ],
                      ),
                    );
                  },
                  itemCount: list.length,
                ));
          } else {
            return Container();
          }
        });
  }
}

class _CustomTabIndicator extends Decoration {
  @override
  BoxPainter createBoxPainter([VoidCallback? onChanged]) {
    return _CustomPainter();
  }
}

class _CustomPainter extends BoxPainter {
  @override
  void paint(Canvas canvas, Offset offset, ImageConfiguration configuration) {
    final Rect rect =
        Offset(offset.dx, offset.dy + configuration.size!.height - 4.0) &
            Size(configuration.size!.width, 4.0);
    final Paint paint = Paint();
    paint.color = Colors.blue; // 设置选中背景色
    paint.style = PaintingStyle.fill;
    canvas.drawRect(rect, paint);
  }
}

class _createTabBarView extends StatefulWidget {
  int activeIndex;
  int index;

  _createTabBarView({Key? key, required this.index, required this.activeIndex})
      : super(key: key);

  @override
  State<_createTabBarView> createState() => _createTabBarViewState();
}

class _createTabBarViewState extends State<_createTabBarView> {
  @override
  Widget build(BuildContext context) {
    // 

    return Container(
      width: 121.0.w,
      // height: 32.0.h,
      padding: const EdgeInsets.only(left: 10, right: 10, top: 3, bottom: 3),
      // decoration: ShapeDecoration(
      //   color: Color(0xFFFFF4F4),
      //   shape: RoundedRectangleBorder(
      //     borderRadius: BorderRadius.circular(22.0.w),
      //   ),
      // ),
      decoration: BoxDecoration(
        // color: _tabController.index == widget.index
        //     ? Colors.transparent
        //     : Colors.grey[300], // 未选中标签背景色
        borderRadius: BorderRadius.circular(22.0.w),
      ),
      child: Align(
        alignment: Alignment.center,
        child: Text(
          widget.index == 0 ? '套餐' : '中震官方教辅',
          textAlign: TextAlign.center,
          style: TextStyle(
            // color: Color(0xFFE6494E),
            fontSize: 15,
            fontFamily: 'PingFang SC',
            fontWeight: FontWeight.w500,
            letterSpacing: 0.28,
          ),
        ),
      ),
    );
  }

  @override
  void dispose() {
    //   dispose
    super.dispose();
  }
}
